package com.thinkgem.jeesite.modules.shop.entity;



import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.FileUtils;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 图片操作工具类
 * 实现图片的上传，删除等功能
 *
 * @author Gaodajiang
 * @version 2013-06-21
 */
public class ImageUtils {

    private static Logger log = LoggerFactory.getLogger(ImageUtils.class);

    /*图片上传*/
    public static String fileUploadImage(HttpServletRequest request) throws Exception {
        String imageaddress = "";
        String path = Global.getConfig("userfiles.upload") + File.separator + "upload" + File.separator + "images" + File.separator + DateFormatUtils.format(new Date(), "yyyy")
                + File.separator + DateFormatUtils.format(new Date(), "MM") + File.separator + DateFormatUtils.format(new Date(), "dd");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> filelist = multipartRequest.getFiles("file");
        if (filelist != null && !filelist.isEmpty()) {
            for (MultipartFile file1 : filelist) {

                CommonsMultipartFile file = (CommonsMultipartFile) file1;

                if (file.getOriginalFilename() != "") {
                    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

                    long fileSize = file.getSize();

                    System.out.println("**************************" + getPrintSize(fileSize));

                    String fileName = UUID.randomUUID().toString() + suffix;
                    // String fileName = filename + suffix;
                    String filePath = path + File.separator + fileName;
//                    String filePath = path + "/" + fileName;+
                    File saveFile = new File(filePath);
                    // 创建目录
                    File parent = saveFile.getParentFile();
                    if (parent != null && !parent.exists()) {
                        parent.mkdirs();
                    }
                    if (!saveFile.exists()) {
                        saveFile.createNewFile();
                    }
                    file.getFileItem().write(saveFile);
                    imageaddress += File.separator + "userfiles" + File.separator + "upload" + File.separator + "images" + File.separator + DateFormatUtils.format(new Date(), "yyyy")
                            + File.separator + DateFormatUtils.format(new Date(), "MM") + File.separator + DateFormatUtils.format(new Date(), "dd") + File.separator + fileName;
//                    imageaddress +=  "/upload/"  + "images/"  + DateFormatUtils.format(new Date(), "yyyy")+"/"
//                            +  DateFormatUtils.format(new Date(), "MM") + DateFormatUtils.format(new Date(), "dd")  + "/"+fileName + ",";
                }
            }
        }
        String imagefile = FileUtils.path(imageaddress);
        return imagefile.substring(0, imagefile.length() - 1);
    }


    /*文件上传，返回上传后的路径、文件大小、文件类型*/
    public static Map<String, Object> fileUpload(HttpServletRequest request) throws Exception {
        String imageaddress = "";
        Map<String, Object> map = Maps.newHashMap();
        String path = Global.getConfig("userfiles.upload") + File.separator + "upload" + File.separator + "images" + File.separator + DateFormatUtils.format(new Date(), "yyyy") + File.separator + DateFormatUtils.format(new Date(), "MM") + File.separator + DateFormatUtils.format(new Date(), "dd");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> filelist = multipartRequest.getFiles("file");
        if (filelist != null && !filelist.isEmpty()) {
            for (MultipartFile file1 : filelist) {
                CommonsMultipartFile file = (CommonsMultipartFile) file1;
                if (file.getOriginalFilename() != "") {
                    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                    long fileSize = file.getSize();

                    map.put("size", getPrintSize(fileSize));//保存文件大小
                    map.put("type", suffix.substring(1, suffix.length()));//保存文件大小

                    String fileName = UUID.randomUUID().toString() + suffix;
                    String filePath = path + File.separator + fileName;
                    File saveFile = new File(filePath);
                    // 创建目录
                    File parent = saveFile.getParentFile();
                    if (parent != null && !parent.exists()) {
                        parent.mkdirs();
                    }
                    if (!saveFile.exists()) {
                        saveFile.createNewFile();
                    }
                    file.getFileItem().write(saveFile);
                    imageaddress += File.separator + "userfiles" + File.separator + "upload" + File.separator + "images" + File.separator + DateFormatUtils.format(new Date(), "yyyy") + File.separator + DateFormatUtils.format(new Date(), "MM") + File.separator + DateFormatUtils.format(new Date(), "dd") + File.separator + fileName;
                }
            }
        }
        String imagefile = FileUtils.path(imageaddress);
        map.put("url", imagefile.substring(0, imagefile.length() - 1));
        return map;
    }


    /*图片上传-自定义路径*/
    public static String fileUploadImage(HttpServletRequest request, String route) throws Exception {
        String imageaddress = "";
        String path = Global.getConfig("userfiles.upload") + File.separator + "upload" + File.separator + "images" + File.separator + route;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> filelist = multipartRequest.getFiles("upfile");
        for (MultipartFile file1 : filelist) {
            CommonsMultipartFile file = (CommonsMultipartFile) file1;
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;
            // String fileName = filename + suffix;
            String filePath = path + File.separator + fileName;
            File saveFile = new File(filePath);
            // 创建目录
            File parent = saveFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            if (!saveFile.exists()) {
                saveFile.createNewFile();
            }
            file.getFileItem().write(saveFile);
            imageaddress += File.separator + "userfiles" + File.separator + "upload" + File.separator + "images" + File.separator + route + File.separator + fileName;
        }
        return FileUtils.path(imageaddress);
    }

    /*录音上传*/
    public static String fileUploadVoice(HttpServletRequest request) throws Exception {
        String voiceaddress = "";
        String path = Global.getConfig("userfiles.upload") + File.separator + "upload" + File.separator + "voice" + File.separator + DateFormatUtils.format(new Date(), "yyyy")
                + File.separator + DateFormatUtils.format(new Date(), "MM") + File.separator + DateFormatUtils.format(new Date(), "dd");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> filelist = multipartRequest.getFiles("voice");
        for (MultipartFile file1 : filelist) {
            CommonsMultipartFile file = (CommonsMultipartFile) file1;
            if (file.getOriginalFilename() != "") {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString() + suffix;
                // String fileName = filename + suffix;
                String filePath = path + File.separator + fileName;
                File saveFile = new File(filePath);
                // 创建目录
                File parent = saveFile.getParentFile();
                if (parent != null && !parent.exists()) {
                    parent.mkdirs();
                }
                if (!saveFile.exists()) {
                    saveFile.createNewFile();
                }
                file.getFileItem().write(saveFile);
                voiceaddress += File.separator + "userfiles" + File.separator + "upload" + File.separator + "voice" + File.separator + DateFormatUtils.format(new Date(), "yyyy")
                        + File.separator + DateFormatUtils.format(new Date(), "MM") + File.separator + DateFormatUtils.format(new Date(), "dd") + File.separator + fileName;
            }
        }
        return FileUtils.path(voiceaddress);
    }

    /*录音上传*/
    public static String fileUploadAppImage(HttpServletRequest request) throws Exception {
        String voiceaddress = "";


        String path = Global.getConfig("userfiles.upload") + File.separator + "upload" + File.separator + "appimage" + File.separator + DateFormatUtils.format(new Date(), "yyyy")
                + File.separator + DateFormatUtils.format(new Date(), "MM") + File.separator + DateFormatUtils.format(new Date(), "dd");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> filelist = multipartRequest.getFiles("img");
        for (MultipartFile file1 : filelist) {
            CommonsMultipartFile file = (CommonsMultipartFile) file1;
            if (file.getOriginalFilename() != "") {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString() + suffix;
                // String fileName = filename + suffix;
                String filePath = path + File.separator + fileName;
                File saveFile = new File(filePath);
                // 创建目录
                File parent = saveFile.getParentFile();
                if (parent != null && !parent.exists()) {
                    parent.mkdirs();
                }
                if (!saveFile.exists()) {
                    saveFile.createNewFile();
                }
                file.getFileItem().write(saveFile);
                voiceaddress += File.separator + "userfiles" + File.separator + "upload" + File.separator + "appimage" + File.separator + DateFormatUtils.format(new Date(), "yyyy")
                        + File.separator + DateFormatUtils.format(new Date(), "MM") + File.separator + DateFormatUtils.format(new Date(), "dd") + File.separator + fileName + ",";
            }
        }
        return FileUtils.path(voiceaddress);
    }

    /*认证借口*/
    public static String fileUploadAuth(HttpServletRequest request, String phone, String name) throws Exception {
        String voiceaddress = "";
        String path = Global.getConfig("userfiles.upload") + File.separator + "upload" + File.separator + "auth" + File.separator + phone;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> filelist = multipartRequest.getFiles(name);
        for (MultipartFile file1 : filelist) {
            CommonsMultipartFile file = (CommonsMultipartFile) file1;
            if (file.getOriginalFilename() != "") {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString() + suffix;
                // String fileName = filename + suffix;
                String filePath = path + File.separator + fileName;
                File saveFile = new File(filePath);
                // 创建目录
                File parent = saveFile.getParentFile();
                if (parent != null && !parent.exists()) {
                    parent.mkdirs();
                }
                if (!saveFile.exists()) {
                    saveFile.createNewFile();
                }
                file.getFileItem().write(saveFile);
                voiceaddress = File.separator + "userfiles" + File.separator + "upload" + File.separator + "auth" + File.separator + phone + File.separator + fileName;
            }
        }
        return FileUtils.path(voiceaddress);
    }

    /**
     * 删除单个文件
     *
     * @param sPath
     * @return
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }


    /**
     * 把字节转换为KB、MB、GB
     *
     * @param size
     * @return
     */
    public static String getPrintSize(long size) {
        //如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        //如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
        //因为还没有到达要使用另一个单位的时候
        //接下去以此类推
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            //因为如果以MB为单位的话，要保留最后1位小数，
            //因此，把此数乘以100之后再取余
            size = size * 100;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "MB";
        } else {
            //否则如果要以GB为单位的，先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "GB";
        }
    }
}
